#pragma once
#include <sys/epoll.h>
#include "Log.hpp"
#include <cstring>
const int default_epfd = -1;
class Epoller
{
public:
    Epoller(int epfd = default_epfd)
    :_epfd(default_epfd)
    {}
    void InitEpoller()
    {
        _epfd = epoll_create(666); //这个参数已经没有意义了
        if(_epfd == default_epfd)
        {
            lg.LogMessage(Error, "epoll create failed, errno: %d: %s\n", errno, strerror(errno));
            exit(-1);
        }
        lg.LogMessage(Info, "epoll create success, epfd: %d\n", _epfd);
    }
    void AddEvent(int sockfd, uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sockfd;
        // std::cout << _epfd << std::endl;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        if(n == -1)
        {
            lg.LogMessage(Error, "epoll add failed, errno: %d: %s\n", errno, strerror(errno));
            return;        
        }
        lg.LogMessage(Info, "epoll add success\n");
    }
    void DelEvent(int sockfd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
        if(n == -1)
        {
            lg.LogMessage(Error, "epoll del failed, errno: %d: %s\n", errno, strerror(errno));
            return;
        }
        lg.LogMessage(Info, "epoll del success\n");
    }

    int Wait(struct epoll_event* revs, int maxevents, int timeout)
    {
        int n = epoll_wait(_epfd, revs, maxevents, timeout);
        return n;
    }
    ~Epoller()
    {
        if(_epfd > 0)
            close(_epfd);
        lg.LogMessage(Info, "close epfd success\n");
    }
private:
    int _epfd;
};